import json

from django.http import HttpResponse, JsonResponse
from django.views.generic import View
from django.shortcuts import redirect


# Create your views here.
def index(request):
    return HttpResponse("ok")


def goods(request, cat_id, goods_id):
    return JsonResponse({'cat_id': cat_id, 'goods_id': goods_id})


# http://127.0.0.1:8000/search/?name=zhang&order=age&order=count
def search(request):
    data = request.GET
    print(data.get("name"))
    print(data.getlist("order"))
    return HttpResponse("ok")
    # zhang
    # ['age', 'count']


def register(request):
    # form表单
    # data = request.POST
    # print(data)

    json_str = request.body
    # json_str = json_str.decode()
    req_data = json.loads(json_str)
    print(req_data)

    print("######################")
    print(request.META)
    return JsonResponse(req_data)


def method(request):
    return HttpResponse(f"请求的方式是{request.method}")


def cookie(request):
    response = HttpResponse("set cookie")
    response.set_cookie('a', 'python1')  # 临时cookie
    response.set_cookie('b', 'python2', max_age=3600)  # 有效期一小时
    return response


def set_session(request):
    data = request.GET
    print(data)
    request.session["name"] = data['name']
    request.session["age"] = data['age']
    return HttpResponse("setSession")


def get_session(request):
    return JsonResponse({
        "name": request.session.get("name"),
        "age": request.session.get("age")
    })


def redirect_baidu(request):
    return redirect('https://www.baidu.com/')


class CenterView(View):

    def get(self, request):
        return HttpResponse("OK")

    def post(self, request):
        return HttpResponse("OK")
